import * as actions from './';

//   import BSPError from './../common/bsperror';
import HttpRequest from './../common/http';

const rootUrl = window.restConfig.rootUrl;

export const initBind = () => {
  return {
    type: actions.BIND_INIT
  }
}

export const sendCode = (mobile) => {  // 这里以后应该还需要一个手机号
  return (dispatch) => {
    HttpRequest.get(rootUrl + '/ensure/code/'+mobile)
      .then((ret) => {
        if (ret.code === 10000) {  // 发送验证码成功与否 应该不弹出东西??
          
        }
      }).catch((err) => {
        dispatch(showError('获取验证码失败'));
      });
  }
}

export const doEnsure = (ifo, callback) => {  // 这里以后应该还需要一个手机号
  return (dispatch) => {
    HttpRequest.post(rootUrl + '/ensure/account', ifo)
      .then((ret) => {
        if (ret.code === 10000) {  // 发送验证码成功与否 应该不弹出东西??
          dispatch({
            type: actions.PERSONAL_INFO_CHANGE,
            data: {
              state: ret.data || {}
            }
          });
          callback();
        }
      }).catch((err) => {
        dispatch(showError('手机号码绑定失败'));
      });
  }
}

export const dataChange = (name, value) => {
  return {
    type: actions.BIND_CHANGE,
    data: {
      data: {
        [name]: value
      }
    }
  }
}

export const stateChange = (name, value) => {
  return {
    type: actions.BIND_CHANGE,
    data: {
      state: {
        [name]: value
      }
    }
  }
}
export const errorChange = (name, value) => {
  return {
    type: actions.BIND_CHANGE,
    data: {
      error: {
        [name]: value
      }
    }
  }
}

export const showError = (text) => {
  return (dispatch) => {
    dispatch(errorChange('hasError', true));
    dispatch(errorChange('msg', text));

    let timer = setTimeout( () => {
      window.clearTimeout(timer);
      dispatch(errorChange('hasError', false));
      dispatch(errorChange('msg', ''));
    }, 2000);
  }
}

export const doSign = (periodId, callback) => {
  return (dispatch) => {
    HttpRequest.post(rootUrl + '/sign', {
      periodId: "ee392901c9b011e7beec814c199c23bc",
    })
      .then((ret) => {
        if (ret.code === 10000) {  // 发送验证码成功与否 应该不弹出东西??
          callback();
        }
      }).catch((err) => {
        dispatch(showError(err.message));
      });
  }
}